package class03;

import java.util.Arrays;

/**
 * 用数组实现队列（循环数组）
 */
public class Code04_RingArray {
    // 数组队列
    public static class ArraysQueue {

        public int[] array;
        public int top;
        public int end;
        public int size;
        public int limit;

        // 初始化参数
        public ArraysQueue(int limit) {
            this.array = new int[limit];
            this.top = 0;
            this.end = 0;
            this.size = 0;
            this.limit = limit;
        }

        // 添加队列
        public void push(int value) {
            if (size == limit) {
                throw new RuntimeException("队列已满");
            }
            size++;
            array[end] = value;
            end = (limit + end + 1) % limit;
        }

        // 移出队列
        public int poll() {
            if (isEmpty()) {
                throw new RuntimeException("队列为空");
            }
            size--;
            int result = array[top];
            top = (limit + top + 1) % limit;
            return result;
        }

        // 队列是否为空
        public boolean isEmpty() {
            return size == 0;
        }
    }

    public static void main(String[] args) {
        ArraysQueue queue = new ArraysQueue(5);
        queue.push(1);
        queue.push(2);
        queue.push(3);
        queue.push(4);
        queue.push(5);
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        queue.push(6);
        queue.push(7);
        queue.push(7);
        System.out.println(Arrays.toString(queue.array));
    }
}
